package interview.loop;

import interview.common.Node;
import interview.recursion.LinkedListCreator;

import java.util.ArrayList;
import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * Description: 循环
 * User: xxm
 * Date: 2018-02-21
 * Time: 0:07
 */
public class LinkedListDeletor {

    /**
     * 删除链表中相同的元素
     *
     * @param head  delete the value from this LinkedList
     * @param value the value need to delete
     * @return
     */
    public Node deleteIfEquals(Node head, int value) {

        while (head != null && head.getValue() == value) {
            head = head.getNext();
        }
        if (head == null) {
            return null;
        }

        Node previous = head;
        while (previous.getNext() != null) {
            if (previous.getNext().getValue() == value) {
                // delete this value
                previous.setNext(previous.getNext().getNext());
            } else {
                previous = previous.getNext();
            }
        }
        return head;
    }

    public static void main(String[] args) {
        LinkedListCreator creator = new LinkedListCreator();
        LinkedListDeletor deletor = new LinkedListDeletor();

        Node.printLinkedList(deletor.deleteIfEquals(
                creator.createLinkedList(Arrays.asList(1, 2, 2, 3, 4)), 2)
        );
        Node.printLinkedList(deletor.deleteIfEquals(
                creator.createLinkedList(Arrays.asList(2, 2, 2, 3, 4)), 2)
        );
        Node.printLinkedList(deletor.deleteIfEquals(
                creator.createLinkedList(Arrays.asList(2)), 2)
        );
        Node.printLinkedList(deletor.deleteIfEquals(
                creator.createLinkedList(Arrays.asList(2)), 1)
        );
        Node.printLinkedList(deletor.deleteIfEquals(
                creator.createLinkedList(Arrays.asList(2, 2, 2, 2, 2, 2)), 2)
        );
        Node.printLinkedList(deletor.deleteIfEquals(
                creator.createLinkedList(Arrays.asList(2, 2, 3, 2, 2)), 2)
        );
        Node.printLinkedList(deletor.deleteIfEquals(
                creator.createLinkedList(new ArrayList<Integer>()), 2)
        );
    }
}
